package com.jp.knowledge.activity;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.dmcc.image_preview.ImagePreviewActivity;
import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.dialog.CopyrightDialog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.ProductUIModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.activity.FeedbackCreateActivity;
import com.jp.knowledge.my.model.CollectionUiModel;
import com.jp.knowledge.my.model.OrganizaModel;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.util.ShareBuilder;
import com.umeng.socialize.media.UMImage;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 528787067@qq.com on 2017/7/26.
 */

public class ImageActivity extends ImagePreviewActivity implements View.OnClickListener, ResultSubscriber.OnResultListener {

	public static void startActivity(Context mContext, int position, int action, List<ProductUIModel> datas) {
		if(position < 0 || datas == null || position >= datas.size()) {
			return;
		}
		ArrayList<String> medias = new ArrayList<>();
		for(ProductUIModel data : datas)
			medias.add(data.getCover()+"?imageMogr2/format/jpg");
		Intent intent = new Intent(mContext, ImageActivity.class);
		intent.putExtra("position", position);
		intent.putExtra("action", action);
		intent.putExtra("extraPics", medias);
		intent.putExtra("datas", (Serializable) datas);
		mContext.startActivity(intent);
	}

	private FrameLayout topBar;
	private LinearLayout bottomBar;
	private ImageView returnBtn;
	private ImageView moreBtn;
	private TextView copyrightBtn;
	private TextView switchBtn;
	private ImageView saveBtn;
	private ImageView gotoBtn;
	private ImageView collectionBtn;
	private ImageView shareBtn;
	private TextView sharePopView;

	private PopupWindow morePopWin;
	private View morePopWinView;
	private TextView feedbackBtn;
	private View splitLine;
	private TextView adjustBtn;

	private int action;
	private List<ProductUIModel> datas;
	private ObjectAnimator topBarAnimator;
	private ObjectAnimator bottomBarAnimator;
	private CopyrightDialog copyrightDialog;
	private PopupWindow sharePopWin;
	private ShareBuilder shareBuilder;

	@Override
	protected void setWindowsFlags(Window window) {
		window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
	}

	@Override
	public int bindLayout() {
		return R.layout.activity_image;
	}

	@Override
	public void initView(View view) {
		action = getIntent() .getIntExtra("action", -1);
		datas = (List<ProductUIModel>) getIntent().getSerializableExtra("datas");
		topBar = (FrameLayout) view.findViewById(R.id.top_bar);
		topBar.setTag(true);
		bottomBar = (LinearLayout) view.findViewById(R.id.bottom_bar);
		returnBtn = (ImageView) view.findViewById(R.id.top_return);
		moreBtn = (ImageView) view.findViewById(R.id.top_more);
		copyrightBtn = (TextView) view.findViewById(R.id.copyright_btn);
		switchBtn = (TextView) view.findViewById(R.id.switch_btn);
		saveBtn = (ImageView) view.findViewById(R.id.save_btn);
		gotoBtn = (ImageView) view.findViewById(R.id.goto_btn);
		collectionBtn = (ImageView) view.findViewById(R.id.collection_btn);
		shareBtn = (ImageView) view.findViewById(R.id.share_btn);
		returnBtn.setOnClickListener(this);
		moreBtn.setOnClickListener(this);
		copyrightBtn.setOnClickListener(this);
		switchBtn.setOnClickListener(this);
		saveBtn.setOnClickListener(this);
		gotoBtn.setOnClickListener(this);
		collectionBtn.setOnClickListener(this);
		shareBtn.setOnClickListener(this);
		switchBtn.setTag(false);
		copyrightDialog = new CopyrightDialog(this);
		initPopWin();
		super.initView(view);
		toolbar.setVisibility(View.GONE);
		UserData userData = ((JpApplication)getApplication()).getUserData();
		if(userData != null && userData.getPlatformAdmin() == 1){
			splitLine.setVisibility(View.VISIBLE);
			adjustBtn.setVisibility(View.VISIBLE);
		} else{
			splitLine.setVisibility(View.GONE);
			adjustBtn.setVisibility(View.GONE);
		}
	}

	private void initPopWin(){
		sharePopView = new TextView(this);
		sharePopView.setBackground(getResources().getDrawable(R.drawable.share_popups));
		sharePopView.setGravity(Gravity.CENTER);
		sharePopView.setText("分享");
		sharePopView.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.xshare, 0, 0, 0);
		sharePopView.setTextColor(getResources().getColor(R.color.white));
		sharePopView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.middle_font));
		sharePopView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
		sharePopView.setOnClickListener(this);
		sharePopWin = new PopupWindow(sharePopView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
		sharePopWin.setOutsideTouchable(true);
		sharePopWin.setBackgroundDrawable(new ColorDrawable(0x00000000));

		morePopWinView = View.inflate(this, R.layout.team_circle_create_popupwindow, null);
		feedbackBtn = (TextView) morePopWinView.findViewById(R.id.team_circle_create_dynamic);
		adjustBtn = (TextView) morePopWinView.findViewById(R.id.team_circle_create_broke);
		splitLine = morePopWinView.findViewById(R.id.split_line);
		feedbackBtn.setText("我要反馈");
		adjustBtn.setText("校正管理");
		feedbackBtn.setOnClickListener(this);
		adjustBtn.setOnClickListener(this);
		morePopWin  = new PopupWindow(morePopWinView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
		morePopWin.setOutsideTouchable(true);
		morePopWin.setBackgroundDrawable(new ColorDrawable(0x00000000));
	}

	@Override
	public void onClick(View v) {
		if(v == returnBtn){
			onBackPressed();
		} else if(v == moreBtn){
			morePopWinView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
			morePopWin.showAsDropDown(moreBtn,
					-morePopWinView.getMeasuredWidth() + moreBtn.getMeasuredWidth(), 0);
		} else if(v == switchBtn){
//			switchBtn.setTag((!(boolean)switchBtn.getTag()));
//			List<String> imageUrls = new ArrayList<>();
//			for(String imgUrl : extraPics){
//				imageUrls.add(imgUrl.substring(0, imgUrl.lastIndexOf('?'))
//						+ ((boolean)switchBtn.getTag()
//						? "?imageView2/1/interlace/1"
//						: "?imageView2/1/interlace/1/format/jpg"));
//			}
//			extraPics.clear();
//			extraPics.addAll(imageUrls);
//			fragmentMap.clear();
//			mImageViewAdapter.notifyDataSetChanged();
//			setMore(viewPager.getCurrentItem());
		} else if(v == saveBtn){
			savePicture();
		} else if(v == gotoBtn){
			Intent intent = new Intent(this, ProductDetailActivity.class);
			intent.putExtra("id", datas.get(viewPager.getCurrentItem()).getProductId());
			intent.putExtra("action", 2);
			startActivity(intent);
		} else if(v == collectionBtn){
			collection(viewPager.getCurrentItem());
		} else if(v == copyrightBtn){
			copyrightDialog.setDesc(datas.get(viewPager.getCurrentItem()).getNotice());
			copyrightDialog.show();
		} else if(v == shareBtn){
			sharePopWin.showAsDropDown(shareBtn,
					-sharePopView.getMeasuredWidth() + shareBtn.getMeasuredWidth(),
					-sharePopView.getMeasuredHeight() - shareBtn.getMeasuredHeight());
		} else if(v == sharePopView){
			sharePopWin.dismiss();
			ProductUIModel data = datas.get(viewPager.getCurrentItem());
			if(shareBuilder == null)
				shareBuilder = new ShareBuilder(this);
			String url = data.getCover();
			shareBuilder.withTitle(data.getName())
					.withText(data.getName())
					.withCopyContent("【" + data.getName() + "】" + url)
					.withTargetUrl(url)
					.withQRCodeUrl(url);
			try{
				shareBuilder.withMedia(new UMImage(this, url));
			} catch (Exception e){
				shareBuilder.withMedia(new UMImage(this, R.mipmap.icon_launcher));
			} finally {
				shareBuilder.build().open();
			}
		} else if(v == feedbackBtn){
			morePopWin.dismiss();
			ProductUIModel data = datas.get(viewPager.getCurrentItem());
			Intent intent = new Intent(this, FeedbackCreateActivity.class);
			intent.putExtra(TeamCircleCreateActivity.INTENT_TYPE, 3);
			intent.putExtra(TeamCircleCreateActivity.INTENT_LEVEL, 1);
			intent.putExtra(TeamCircleCreateActivity.INTENT_LINK_ICON, data.getCover());
			intent.putExtra(TeamCircleCreateActivity.INTENT_LINK_ID, data.getProductId());
			intent.putExtra(TeamCircleCreateActivity.INTENT_LINK_TITLE, data.getName());
			intent.putExtra(TeamCircleCreateActivity.INTENT_LINKK_TYPE, data.getType());
			startActivity(intent);
		} else if(v == adjustBtn){
			morePopWin.dismiss();
			startActivity(new Intent(this, AdjustSortImageActivity.class)
					.putExtra("id", datas.get(viewPager.getCurrentItem()).getId())
					.putExtra("action", action));
		}
	}

	@Override
	protected void initCurrentItem(int position) {
		super.initCurrentItem(position);
		setMore(position);
	}

	@Override
	public void onPageSelected(int position) {
		super.onPageSelected(position);
		setMore(position);
	}

	@Override
	public void onPageClick() {
		boolean showed = (boolean) topBar.getTag();
		topBar.setTag(!showed);
		if(topBarAnimator != null)
			topBarAnimator.cancel();
		if(bottomBarAnimator != null)
			bottomBarAnimator.cancel();
		topBarAnimator = ObjectAnimator.ofFloat(topBar, "translationY",
				topBar.getTranslationY(), showed ? -topBar.getHeight() : 0);
		bottomBarAnimator = ObjectAnimator.ofFloat(bottomBar, "translationY",
				bottomBar.getTranslationY(), showed ? mContextView.getHeight() : 0);
		topBarAnimator.setDuration(200);
		bottomBarAnimator.setDuration(200);
		topBarAnimator.start();
		bottomBarAnimator.start();
	}

	private void setMore(int position){
		switchBtn.setText((position + 1) + "/" + mImageViewAdapter.getCount()/* + ((boolean)switchBtn.getTag() ? "(高清)" : "(标清)")*/);
		if(datas.get(position).getIsFollow() == 1)
			collectionBtn.setImageResource(R.mipmap.red_star);
		else
			collectionBtn.setImageResource(R.mipmap.stars);
		if(TextUtils.isEmpty(datas.get(viewPager.getCurrentItem()).getNotice()))
			copyrightBtn.setVisibility(View.GONE);
		else
			copyrightBtn.setVisibility(View.VISIBLE);
	}

	private void collection(int position){
		CollectionUiModel uiModel = datas.get(position);
		JsonObject param = new JsonObject();
		param.addProperty("token", HttpHelper.token);
		param.addProperty("id", uiModel.getId());
		param.addProperty("type", 15);
		if(uiModel.getIsFollow() == 1) {
			HttpHelper.getInstance(this).unCollection(param, position, this);
		} else{
			HttpHelper.getInstance(this).collectionHead(param, position, this);
		}
		uiModel.setIsFollow(uiModel.getIsFollow()==1 ? 0 : 1);
		setMore(position);
	}

	@Override
	public void onStart(int requestType) {}
	@Override
	public void onCompleted(int requestType) {}
	@Override
	public void onError(int requestType) {
		CollectionUiModel uiModel = datas.get(requestType);
		uiModel.setIsFollow(uiModel.getIsFollow()==1 ? 0 : 1);
		setMore(requestType);
	}
	@Override
	public void onNext(IModel data, int requestType) {
		if(data.getErrcode() != 0){
			ToasUtil.toast(this, data.getMessage());
			onError(requestType);
		} else{
			LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(LocalBroadCast.DETAIL_SC_BROAD)
					.putExtra("id", datas.get(requestType).getId())
					.putExtra("isCollection", datas.get(requestType).getIsFollow()));
		}
	}
}
